﻿/*
Copyright (c) 2011 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.Collections.Generic;
using System.Drawing;

namespace TeachMe.Application
{
    public class ObjectFactoryWrappers
    {
        public static Font CreateFont(FontFamily family, float size, FontStyle style)
        {
            return ObjectsFactory<Font>.Find(x => x.FontFamily == family && x.Size == size && x.Style == style, () => new Font(family, size, style));
        }
    }
    
    public class ObjectsFactory<T> where T : class
    {
        public static T Find(Predicate<T> match, CreateDelegate createDelegate)
        {
            return Singleton<ObjectsFactory<T>>.Instance.InternalFind(match, createDelegate);
        }

        private Dictionary<Type, List<T>> _data = new Dictionary<Type, List<T>>();

        public delegate T CreateDelegate();

        private T InternalFind(Predicate<T> match, CreateDelegate createDelegate)
        {
            Type type = typeof(T);
            if (!_data.ContainsKey(type))
            {
                _data.Add(type, new List<T>());
            }
            T result = _data[typeof(T)].Find(match);
            if (result == null)
            {
                result = createDelegate();
                _data[type].Add(result);
            }
            return result;
        }
    }
}
